package com.lambda.hybrid.handler;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.res.Resources;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.lambda.hybrid.Callback;
import com.lambda.hybrid.R;

import org.json.JSONObject;

public class TextHUDHandler extends AbstractHandler implements Animator.AnimatorListener {
    private final FrameLayout mParentView;
    private TextView mTextHud;
    private ObjectAnimator mAnim;

    public TextHUDHandler(FrameLayout parent) {
        mParentView = parent;
    }

    /**
     * {
     * text: "text",
     * duration: 1200,
     * bottom: false
     * }
     *
     * @param data
     * @param callback
     * @throws Exception
     */
    @Override
    public void onHandle(String data, Callback callback) throws Exception {
        if (mParentView == null) return;

        if (mTextHud == null) {
            LayoutInflater.from(mParentView.getContext()).inflate(R.layout.layout_text_hud, mParentView, true);
            mTextHud = mParentView.findViewById(R.id.hybrid_text_hud);
            mTextHud.setVisibility(View.GONE);
        }

        JSONObject prefs = new JSONObject(data);
        String text = prefs.getString("text");
        if (text.length() > 512) text = text.substring(0, 512);
        mTextHud.setText(text);
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mTextHud.getLayoutParams();
        if (prefs.optBoolean("bottom")) {
            params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
            Resources resources = mParentView.getResources();
            params.bottomMargin = 64 * Math.round(resources.getDisplayMetrics().density);
        } else {
            params.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL;
            params.bottomMargin = 0;
        }
        mTextHud.setLayoutParams(params);
        mTextHud.clearAnimation();

        mTextHud.setVisibility(View.VISIBLE);
        mTextHud.setAlpha(1);

        if (mAnim == null) {
            mAnim = ObjectAnimator.ofFloat(mTextHud, View.ALPHA, 1, 0);
            mAnim.setDuration(333);
        } else {
            mAnim.cancel();
        }
        mAnim.setStartDelay(prefs.optInt("duration", 1200));
        mAnim.start();

        callback.invoke("{\"success\":true}");
    }


    @Override
    public void onAnimationStart(Animator animation) {
    }

    @Override
    public void onAnimationEnd(Animator animation) {
        mTextHud.setVisibility(View.GONE);
    }

    @Override
    public void onAnimationCancel(Animator animation) {

    }

    @Override
    public void onAnimationRepeat(Animator animation) {

    }
}
